<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="请你输入SPU名称" v-model="SpuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option v-for="item in AllTradeMark" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" placeholder="请输入描述" v-model="SpuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU照片">
      <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handleUpload">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrIdAndName" :placeholder="unSelectSaleAttr ? `还未选择${unSelectSaleAttr.length}个` : '无'">
        <el-option :value="`${item.id}:${item.name}`" v-for="item in unSelectSaleAttr" :key="item.id"
          :label="item.name"></el-option>
      </el-select>
      <el-button :disabled="saleAttrIdAndName ? false : true" style="margin-left: 10px;" type="primary" icon="Plus"
        @click="addSaleAttr">添加属性值</el-button>
      <el-table border style="margin: 10px 0;" :data="saleAttr">
        <el-table-column label="序号" type="index" align="center" width="100px">
        </el-table-column>
        <el-table-column label="属性名" align="center" width="100px" prop="saleAttrName">
        </el-table-column>
        <el-table-column label="属性值">
          <template #default="{ row }">
            <el-tag @close="row.spuSaleAttrValueList.splice(index, 1)" v-for="(item, index) in row.spuSaleAttrValueList"
              :key="row.id" closable style="margin: 0 10px;">
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input v-model="row.saleAttrValueName" @blur="toLook(row)" @keyup.enter="toLook(row)"
              v-if="row.flag == true" placeholder="请输入属性值" size="small" style="width: 120px;"></el-input>
            <el-button @click="toEdit(row)" v-else type="success" size="small" icon="Plus"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template #="{ row, $index }">
            <el-button type="danger" icon="Delete" @click="saleAttr.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reqAllSaleAttr, reqAllTradeMark, reqImageList, reqSpuHasSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu';
import { SpuData, SpuHasImg, AllTradeMark, HasSaleAttrResponseData, SaleAttrResponseData, spuImg, tradeMark, SaleAttr, HasSaleAttr } from '@/api/product/spu/type';
import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';

let $emit = defineEmits(['changeScene'])

//#region 数据定义
// 存储已有的SPU数据
let AllTradeMark = ref<tradeMark[]>([])
// 商品照片
let imgList = ref<spuImg[]>([])
// SPU销售属性
let saleAttr = ref<SaleAttr[]>([])
// 全部销售属性
let allSaleAttr = ref<HasSaleAttr[]>()
// 控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
// 预览图片地址
let dialogImageUrl = ref<string>('')
// 已有Spu对象
let SpuParams = ref<SpuData>({
  category3Id: "",
  description: "",
  spuName: "",
  "spuImageList": [],
  "spuSaleAttrList": [],
  "tmId": ''
})
//#endregion

// 还未选择的销售属性id和名字
let saleAttrIdAndName = ref<string>('')
// 取消按钮回调
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}

// 更新SPU初始化请求
const initHasSpuData = async (spu: SpuData) => {
  SpuParams.value = spu
  let result: AllTradeMark = await reqAllTradeMark()
  let result1: SpuHasImg = await reqImageList(spu.id as number)
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  AllTradeMark.value = result.data
  saleAttr.value = result2.data
  allSaleAttr.value = result3.data
  imgList.value = result1.data.map((item: any) => {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
}

// 照片墙点击预览按钮的回调
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 照片墙删除文件按钮回调
const handleRemove = () => {

}

// 照片上传之前约束大小类型
const handleUpload = (file: any) => {
  if (
    file.type == "image/png" ||
    file.type == "image/jpeg" ||
    file.type == "image/gif"
  ) {
    if (file.size / 1024 < 30) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小应小于30K",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件类型必须是PNG|JPG|GIF",
    });
    return false;
  }
}

// 当前SPU还未拥有的销售属性
let unSelectSaleAttr: SaleAttr = computed(() => {
  return allSaleAttr.value?.filter(item => {
    return saleAttr.value.every((item1: any) => {
      return item.name != item1.saleAttrName
    })
  })
})

// 添加销售属性按钮回调
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndName.value.split(':')
  let newSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  saleAttr.value.push(newSaleAttr)
  saleAttrIdAndName.value = ''
}

// 添加属性值按钮回调
const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValueName = ''
}

// 表单失去焦点回调
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValueName } = row
  let newSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName
  }
  if (saleAttrValueName.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return
  }
  let repeat = row.spuSaleAttrValueList.find((item: SaleAttr) => {
    return item.saleAttrValueName == saleAttrValueName
  })
  if (repeat) {
    ElMessage({
      type: "error",
      message: '属性值重复'
    })
    return
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}

// 保存按钮回调
const save = async () => {
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url
    }
  });
  SpuParams.value.spuSaleAttrList = saleAttr.value;
  let result = await reqAddOrUpdateSpu(SpuParams.value);
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功'
    })
    $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' });
  } else {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功'
    })
  }
}

// 添加新的SPU初始化请求
const initAddSpu = async (c3Id: number | string) => {
  Object.assign(SpuParams.value, {
    category3Id: "",
    description: "",
    spuName: "",
    "spuImageList": [],
    "spuSaleAttrList": [],
    "tmId": ''
  })
  imgList.value = []
  saleAttr.value = []
  saleAttrIdAndName.value = ''
  SpuParams.value.category3Id = c3Id
  SpuParams.value.id = ''
  let result: AllTradeMark = await reqAllTradeMark()
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr()

  AllTradeMark.value = result.data
  allSaleAttr.value = result1.data
}


defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped>
.el-select {
  width: 30%;
}
</style>